<template>
  <div class="question-detail">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="title"
    ></white-header>
    <div class="test-time" v-if="had_question_bank">
      <img class="countdown" src="/img/mobile/countdown.png" alt="" />
      <div class="test-msg" v-show="isSetCountdown">
        <span>考试倒计时</span>
        <span class="day-box mgl">{{ countdown[0] }}</span>
        <span class="day-box">{{ countdown[1] }}</span>
        <span class="day-box">{{ countdown[2] }}</span>
        <span class="day-box mgr">{{ countdown[3] }}</span>
        <span>天 </span>
      </div>
      <div
        class="update-time"
        v-show="isSetCountdown"
        @click="isSetting = true"
      >
        修改时间
      </div>
      <div class="test-msg" v-show="!isSetCountdown">
        <span>考试倒计时，请设置考试时间</span>
      </div>
      <div
        class="setting-time"
        @click="isSetting = true"
        v-show="!isSetCountdown"
      >
        设置
      </div>
    </div>
    <div class="slogan">
      <img src="/img/mobile/slogan.png" alt="" />
    </div>
    <div class="menu-list">
      <router-link
        :to="{
          path: had_question_bank
            ? '/m/v2-chapter-practice?id=' + questionId
            : $route.fullPath
        }"
      >
        <div class="menu-item">
          <img
            class="menu-logo"
            src="/img/mobile/question_chapter.png"
            alt=""
          />
          <div class="menu-title">
            <p class="t-name">章节练习</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
      <router-link
        :to="{
          path: had_question_bank
            ? '/m/v2-simulation-test?type=1&id=' + questionId
            : $route.fullPath
        }"
      >
        <div class="menu-item">
          <img
            class="menu-logo"
            src="/img/mobile/question_special.png"
            alt=""
          />
          <div class="menu-title">
            <p class="t-name">专项训练</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
      <router-link
        :to="{
          path: had_question_bank
            ? '/m/v2-simulation-test?type=2&id=' + questionId
            : $route.fullPath
        }"
      >
        <div class="menu-item">
          <img
            class="menu-logo"
            src="/img/mobile/question_simulation.png"
            alt=""
          />
          <div class="menu-title">
            <p class="t-name">模拟考试</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
      <router-link
        :to="{
          path: had_question_bank
            ? '/m/v2-my-mistake?id=' + questionId
            : $route.fullPath
        }"
      >
        <div class="menu-item">
          <img class="menu-logo" src="/img/mobile/question_wrong.png" alt="" />
          <div class="menu-title">
            <p class="t-name">我的错题</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
      <router-link
        :to="{
          path: had_question_bank
            ? '/m/v2-simulation-test?type=3&id=' + questionId
            : $route.fullPath
        }"
      >
        <div class="menu-item">
          <img class="menu-logo" src="/img/mobile/question_true.png" alt="" />
          <div class="menu-title">
            <p class="t-name">真题训练</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
      <router-link :to="{ path: '/m/v2-test-information?id=' + questionId +'&menuType=1'}">
        <div class="menu-item">
          <img class="menu-logo" src="/img/mobile/question_info.png" alt="" />
          <div class="menu-title">
            <p class="t-name">考试资讯</p>
            <p class="t-info">多练习学得快学得好</p>
          </div>
        </div>
      </router-link>
    </div>
    <div class="test-time-setting" v-show="isSetting">
      <div class="test-time-box">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="handleSubmit"
          @cancel="cancelTestTime"
        />
      </div>
    </div>
    <div
      class="footer-buy-btn"
      v-if="!is_hidden_content && !is_show_price && !had_question_bank"
    >
      <div class="buy-btn" @click="handleBuy">
        立即{{ isMemberFreeQuestion || questionDetail.isFree ? "获取" : "购买" }}
      </div>
    </div>
    <div class="switch-btn" @click="isShowToggleQuestion = true">
      切换
    </div>
    <div class="toggle-question-content" v-show="isShowToggleQuestion">
      <div class="toggle-bg" @click="isShowToggleQuestion = false"></div>
      <van-action-sheet v-model="isShowToggleQuestion" :overlay="false">
        <div class="content">
          <div
            :class="[
              'question-item',
              item.id == questionId ? 'selected' : null
            ]"
            @click.stop="toggleQuestion(item)"
            v-for="(item, index) in questionBankList"
            :key="'questionBankList' + index"
          >
            {{ (item && item.questionGroupName) || "未知" }}
          </div>
        </div>
      </van-action-sheet>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import {
  getQuestionBankList,
  getQuestionBankOne,
  getCountDownTime,
  saveCountDownTime,
  updateCountDownTime
} from "~/api/v2-question-bank/question-bank";
import { buyQuestionBank } from "~/api/v2-question-bank/order.js";
export default {
  components: {
    WhiteHeader
  },
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      isSetting: false,
      isShowToggleQuestion: false,
      countdown: "0000", //默认倒计时
      isSetCountdown: false, //是否已经设置过倒计时
      /* 题库列表 */
      questionBankList: [],
      /* 题库相关 */
      questionBank: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      /* 题库详情 */
      questionDetail: {
        isFree: 0,
        questionGroupName: "",
        isDiscount: 0,
        discountPrice: 0,
        price: 0,
        discountEndTime: 0,
        discountStartTime: 0,
        isFree: 0,
        questionGroupName: "",
        startTime: 0,
        endTime: 0,
        isLong: 0
      },
      /* 倒计时详情 */
      countDownObj: {},
      /* 定时器 */
      timer: null
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      myQuesionBankList(state) {
        return state.questionBank.question_record_list;
      },
      token(state) {
        return state.token;
      },
      kl_md(state) {
        return state.kl_md;
      },
      is_ios(state) {
        return state.is_ios;
      },
      is_hidden_content(state) {
        return state.is_hidden_content;
      },
      is_wechat_ios_limit(state) {
        return state.is_wechat_ios_limit;
      },
      is_hidden_for_ios(state) {
        return state.is_hidden_for_ios;
      },
      is_in_minigram(state) {
        return state.is_in_minigram;
      },
      member_discount(state) {
        return state.member_discount;
      },
    }),
    // 是否会员免费题库
    isMemberFreeQuestion(){
      if(Object.keys(this.member_discount).length > 0){
        const { deleted , questionGroupIds } = this.member_discount;
        return deleted == 0 && questionGroupIds.includes(Number(this.questionId));
      }else{
        return false;
      }
    },
    is_show_price() {
      if (this.is_wechat_ios_limit) {
        return this.is_ios && this.is_in_wechat;
      } else {
        return false;
      }
    },
    title() {
      return "题库详情 - " + this.questionDetail.questionGroupName || "";
    },
    had_question_bank() {
      let result = this.myQuesionBankList.filter(i => i.id == this.questionId && i.isDelete != 1);
      if (result && result.length > 0) {
        return true;
      } else {
        return false;
      }
    },
    questionId() {
      return this.$route.query.id;
    }
  },
  watch: {
    // $route(new_val, old_val) {
    //   if (
    //     new_val.path === old_val.path &&
    //     new_val.fullPath != old_val.fullPath
    //   ) {
    //     this.initPage();
    //   }
    // }
  },
  methods: {
    ...mapActions(["getMineV2QuestionBankList"]),
    ...mapMutations(["SET_IS_LOADING", "UPDATE_QUESTION_LIST"]),
    confirmTestTime(value) {
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let date = value.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (date < 10) {
        date = "0" + date;
      }
      let newDate =
        new Date().getFullYear() +
        "-" +
        (new Date().getMonth() + 1) +
        "-" +
        new Date().getDate(); //现在时间
      let future = year + "-" + month + "-" + date; //未来时间
      let day = this.daysDistance(newDate, future) + "";
      if (day.length === 1) {
        this.countdown = "000" + day;
      } else if (day.length === 2) {
        this.countdown = "00" + day;
      } else if (day.length === 3) {
        this.countdown = "0" + day;
      } else if (day.length === 4) {
        this.countdown = day;
      } else {
        this.countdown = "0000";
      }
      let current = new Date().getTime();
      if (value.getTime() <= current) {
        this.timer && clearInterval(this.timer);
      }
    },
    //date1和date2是yyyy-mm-dd格式
    daysDistance(date1, date2) {
      //parse() 是 Date 的一个静态方法 , 所以应该使用 Date.parse() 来调用，而不是作为 Date 的实例方法。返回该日期距离 1970/1/1 午夜时间的毫秒数
      date1 = Date.parse(date1);
      date2 = Date.parse(date2);
      //计算两个日期之间相差的毫秒数的绝对值
      var ms = Math.abs(date2 - date1);
      //毫秒数除以一天的毫秒数,就得到了天数
      var days = Math.floor(ms / (24 * 3600 * 1000));
      return days;
    },
    cancelTestTime() {
      this.isSetting = false;
    },
    toggleQuestion(item) {
      if (item.id != this.questionId) {
        this.$router.replace({
          path: "",
          query: {
            id: item.id
          }
        });
      }
      // this.initPage();
      this.isShowToggleQuestion = false;
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}年${_date.getMonth() +
          1}月${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return this.$t("locale.components.mobile.GroupChat.t7");
      }
    },
    /* 获取题库列表 */
    async getQuestionBanks() {
      this.SET_IS_LOADING(true);
      const { total, page, pageSize } = this.questionBank;
      let params = {
        offset: (page - 1) * pageSize,
        limit: pageSize,
        sort: "id desc"
      };
      let result = await getQuestionBankList(params);
      console.log("题库列表：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows, total, records } = result.data.data;
        this.questionBankList = rows;
        this.questionBank = {
          ...this.questionBank,
          total
        };
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
      }
    },
    /* 购买按钮事件 */
    handleBuy() {
      if (Object.keys(this.user_info).length == 0 || !this.token) {
        this.$router.push({
          path: "/m/login"
        });
      }
      const {
        isDiscount,
        discountPrice,
        price,
        discountEndTime,
        discountStartTime,
        isFree,
        questionGroupName,
        startTime,
        endTime,
        isLong
      } = this.questionDetail;
      let params = {
        userId: this.user_info.id,
        questionGroupId: this.questionId,
        ip: returnCitySN.cip
      };
      let current_time = new Date().getTime();
      let discount_start_time = new Date(discountStartTime).getTime();
      let discount_end_time = new Date(discountEndTime).getTime();
      let start_time = new Date(startTime).getTime();
      let end_time = new Date(endTime).getTime();
      let msg = "";
      /* 长期允许购买 */
      if (isLong) {
        // nothing to do
      } else {
        /* 还未到可以购买的日期 */
        if (current_time < start_time) {
          let _time_ = this.trimDate(start_time);
          this.$dialog.alert({
            title: "提示",
            confirmButtonText: "确认",
            message: `未到题库开放购买时间哦~  如需购买请等待到${_time_}`
          });
          return;
        } else if (current_time >= end_time) {
          let _time_ = this.trimDate(end_time);
          this.$dialog.alert({
            title: "提示",
            confirmButtonText: "确认",
            message: `已超过题库开放购买时间哦~`
          });
          return;
        }
      }
      if (this.isMemberFreeQuestion || isFree) {
        params = {
          ...params,
          price: 0
        };
        msg = `您确定要获取题库《${questionGroupName}》吗？`;
        this.$dialog
          .confirm({
            title: "提示",
            message: msg,
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          })
          .then(async () => {
            this.SET_IS_LOADING(true);
            let result = await buyQuestionBank(params);
            // console.log("题库购买：", result);
            if (result && result.data && result.data.code == 200) {
              this.$toast("获取成功！");
              this.getMineV2QuestionBankList();
            } else {
              if (result && result.data && result.data.code == 420) {
                this.$toast("余额不足，购买失败!");
              } else if (result && result.data && result.data.code == 1001) {
                this.$toast(result.data.msg);
              } else {
                this.$toast("购买失败，请稍后重试！");
              }
            }
            this.SET_IS_LOADING(false);
          })
          .catch(() => {
            // on cancel
          });
      }else{
        this.$router.push({
          path: "/m/v2-question-purchase?qid="+this.questionId
        });
      }
      return;
      /* 免费 */
      if (isFree) {
        params = {
          ...params,
          price: 0
        };
        msg = `您确定要获取题库《${questionGroupName}》吗？`;
      } else {
        /* 折扣价 */
        if (
          isDiscount == 1 &&
          discount_start_time <= current_time &&
          current_time < discount_end_time
        ) {
          params = {
            ...params,
            price: discountPrice
          };
          /* 原价 */
        } else {
          params = {
            ...params,
            price
          };
        }
        msg = `您确定要支付${params.price}元购买题库《${questionGroupName}》吗？`;
      }
      this.$dialog
        .confirm({
          title: "提示",
          message: msg,
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        })
        .then(async () => {
          this.SET_IS_LOADING(true);
          let result = await buyQuestionBank(params);
          console.log("题库购买：", result);
          if (result && result.data && result.data.code == 200) {
            this.$toast("购买成功！");
            this.getMineV2QuestionBankList();
          } else {
            if (result && result.data && result.data.code == 420) {
              this.$toast("余额不足，购买失败!");
            } else if (result && result.data && result.data.code == 1001) {
              this.$toast(result.data.msg);
            } else {
              this.$toast("购买失败，请稍后重试！");
            }
          }
          this.SET_IS_LOADING(false);
        })
        .catch(() => {
          // on cancel
        });
    },
    /* 获取当前题库 */
    async getQuestionBankOne() {
      this.SET_IS_LOADING(true);
      let result = await getQuestionBankOne(this.questionId);
      console.log("获取当前题库：", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          this.questionDetail = data;
        }
      }
      this.SET_IS_LOADING(false);
    },
    /* 获取考试倒计时 */
    async getCountDownTime() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id,
        questionGroupId: this.questionId
      };
      let result = await getCountDownTime(params);
      console.log("获取考试倒计时：", result);
      if (result && result.data && result.data.code == 200) {
        const { rows } = result.data.data;
        if (rows.length > 0) {
          this.currentDate = new Date(rows[0].time);
          this.countDownObj = rows[0];
          this.timer = setInterval(() => {
            this.confirmTestTime(this.currentDate);
          }, 1000);
          this.isSetting = false;
          this.isSetCountdown = true;
        }
      }
      this.SET_IS_LOADING(false);
    },
    /* 保存考试倒计时 */
    async saveCountDownTime() {
      this.SET_IS_LOADING(true);
      let value = this.currentDate;
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let date = value.getDate();
      let time = year + "-" + month + "-" + date;
      let params = {
        userId: this.user_info.id,
        questionGroupId: this.questionId,
        time
      };
      let result = await saveCountDownTime(params);
      console.log("保存考试倒计时：", result);
      if (result && result.data && result.data.code == 200) {
        this.countDownObj = result.data.data;
        this.timer = setInterval(() => {
          this.confirmTestTime(this.currentDate);
        }, 1000);
        this.isSetting = false;
        this.isSetCountdown = true;
      }
      this.SET_IS_LOADING(false);
    },
    /* 修改考试倒计时 */
    async updateCountDownTime() {
      this.SET_IS_LOADING(true);
      let value = this.currentDate;
      let year = value.getFullYear();
      let month = value.getMonth() + 1;
      let date = value.getDate();
      let time = year + "-" + month + "-" + date;
      let params = {
        id: this.countDownObj.id,
        userId: this.user_info.id,
        questionGroupId: this.questionId,
        time
      };
      let result = await updateCountDownTime(params);
      console.log("保存考试倒计时：", result);
      if (result && result.data && result.data.code == 200) {
        this.countDownObj = result.data.data;
        this.timer = setInterval(() => {
          this.confirmTestTime(this.currentDate);
        }, 1000);
        this.isSetting = false;
        this.isSetCountdown = true;
      }
      this.SET_IS_LOADING(false);
    },
    /* 设置考试倒计时 */
    handleSubmit() {
      if (Object.keys(this.countDownObj).includes("id")) {
        this.updateCountDownTime();
      } else {
        this.saveCountDownTime();
      }
    },
    initPage() {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        return this.$router.replace("/m/login");
      }
      this.getCountDownTime();
      this.getQuestionBanks();
      this.getQuestionBankOne();
      this.getMineV2QuestionBankList();
    }
  },
  created() {
    // this.initPage();
  },
  activated() {
    this.initPage();
  },
  deactivated() {
    this.timer && clearInterval(this.timer);
  },
  destroyed() {
    this.timer && clearInterval(this.timer);
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.question-detail {
  background-color: #f7f7fa;
  min-height: 100vh;
  width: 7.2rem;
  .bottom-area {
    height: 1rem;
    .van-submit-bar {
      box-shadow: 0 0 0.1rem 0 rgba(0, 0, 0, 0.1);
    }
  }
  .test-time {
    width: 7.2rem;
    height: 1.728rem;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    .setting-time {
      margin-left: 0.3rem;
      width: 1.056rem;
      height: 0.4416rem;
      border-radius: 0.2208rem;
      text-align: center;
      line-height: 0.4416rem;
      font-size: 0.2496rem;
      color: #ffffff;
      background: var(--theme-color);
    }
    .countdown {
      width: 0.48rem;
      height: 0.48rem;
      display: block;
      // background: var(--theme-color);
      background: var(--theme-color);
    }
    .test-msg {
      margin: 0 0.2rem;
      color: #4a4b4d;
      font-size: 0.3072rem;
      font-weight: bold;
      display: flex;
      align-items: center;
      .day-box {
        display: inline-block;
        width: 0.5184rem;
        height: 0.5184rem;
        margin: 0 0.05rem;
        background-image: linear-gradient(180deg, #eaebec 0%, #f7f8fa 100%),
          linear-gradient(#ffffff, #ffffff);
        border-radius: 0.0384rem;
        color: var(--theme-color);
        text-align: center;
        line-height: 0.5184rem;
        position: relative;
        &::after {
          content: "";
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          display: block;
          width: 0.5184rem;
          height: 0.02rem;
          background: #ffffff;
        }
        &.mgl {
          margin-left: 0.1rem;
        }
        &.mgr {
          margin-right: 0.1rem;
        }
      }
    }
    .update-time {
      font-size: 0.2496rem;
      font-weight: bold;
      color: var(--theme-color);
    }
  }
  .slogan {
    width: 7.2rem;
    img {
      display: block;
      height: 1.488rem;
      width: 6.7968rem;
      margin: 0.2rem auto;
    }
  }
  .menu-list {
    overflow: hidden;
    .menu-item {
      width: 3.168rem;
      height: 1.536rem;
      float: left;
      margin-left: 0.288rem;
      margin-top: 0.288rem;
      background-color: #ffffff;
      border-radius: 0.1152rem;
      display: flex;
      align-items: center;
      justify-content: center;
      .menu-logo {
        width: 0.768rem;
        height: 0.768rem;
        display: block;
      }
      .menu-title {
        width: 2rem;
        height: 0.768rem;
        padding-top: 0.06rem;
        margin-left: 0.05rem;
        .t-name {
          color: #4a4b4d;
          font-size: 0.288rem;
          font-weight: bold;
        }
        .t-info {
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: #b1b1b3;
          line-height: 0.3rem;
          font-size: 0.22rem;
        }
      }
    }
  }
  .test-time-setting {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 2001;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    .test-time-box {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 5.76rem;
      height: 3.36rem;
      background-color: #ffffff;
      border-radius: 0.1344rem;
    }
  }
  .switch-btn {
    position: fixed;
    right: 0.258rem;
    top: 0.258rem;
    width: 0.768rem;
    height: 0.384rem;
    border-radius: 0.192rem;
    text-align: center;
    line-height: 0.384rem;
    background: var(--theme-color);
    color: #fff;
    font-size: 0.2112rem;
    z-index: 2001;
  }
  .toggle-question-content {
    .toggle-bg {
      position: fixed;
      top: 0.9rem;
      left: 0;
      z-index: 2001;
      width: 100%;
      height: calc(100% - 0.9rem);
      background-color: rgba(0, 0, 0, 0.7);
    }
    .content {
      padding: 0.4rem 0.288rem 0;
      .question-item {
        width: 100%;
        height: 0.8448rem;
        background-color: #f2f3f5;
        border-radius: 0.096rem;
        margin-bottom: 0.288rem;
        color: #929496;
        font-size: 0.3072rem;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        padding: 0 0.2rem;
        line-height: 0.8448rem;
        &.selected {
          background: var(--theme-color);
          color: #fff;
        }
      }
    }
  }
  .footer-buy-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 7.2rem;
    height: 0.9984rem;
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    .buy-btn {
      width: 6.624rem;
      height: 0.768rem;
      border-radius: 0.384rem;
      background: var(--theme-color);
      color: #ffffff;
      font-size: 0.3rem;
      text-align: center;
      line-height: 0.768rem;
    }
  }
}
</style>
